package com.ruoyi.web.controller.tool;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.config.WxConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.HttpUtil;
import com.ruoyi.system.domain.JzToursUser;
import com.ruoyi.system.domain.vo.WxLoginVo;
import com.ruoyi.system.mapper.JzToursUserMapper;
import com.ruoyi.system.service.IJzToursUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Api("微信登陆相关")
@RestController
@RequestMapping("/front/login")
public class WxLoginController {

    @Autowired
    private IJzToursUserService jzToursUserService;


    @ApiOperation("微信小程序登陆")
    @PostMapping
    @ResponseBody
    public AjaxResult mini_Login(HttpServletRequest request, @RequestBody WxLoginVo code) {
        //String c=request.getParameter("code");//也可以通过此语句获取code值
        //System.out.println(code);
        AjaxResult res = new AjaxResult();//这里是自定义类，用于封装返回的数据，你可以用map替代
        String result = "";
        try {//请求微信服务器，用code换取openid。HttpUtil是工具类，后面会给出实现，Configure类是小程序配置信息，后面会给出代码
            result = HttpUtil.doGet(
                    "https://api.weixin.qq.com/sns/jscode2session?appid="
                            + WxConfig.mini_appID + "&secret="
                            + WxConfig.mini_secret + "&js_code="
                            + code.getCode()
                            + "&grant_type=authorization_code", null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //System.out.println(result);
        JSONObject jsonObj = JSONObject.parseObject(result);//解析从微信服务器上获取到的json字符串
        System.out.println("用户的openid为：" + jsonObj.get("openid"));//此处也可以得到session_key的值
        res.put("session_key", jsonObj.get("session_key").toString());
          //这里Miniuser类是自己的业务类，你可以根据自己需要自行定义
       JzToursUser miniuser =jzToursUserService.selectJzToursUserByOpenId(jsonObj.get("openid").toString());//去数据库判断用户是否存在该用户
        if (miniuser != null)//如果存在该用户
        {
            res.put("userid", miniuser.getId());//将用户id返回
             return AjaxResult.success(res);
        }
        //如果是新用户，就添加用户到数据库中
        JzToursUser userInfo = new JzToursUser();//封装小程序对象
        userInfo.setOpenId(jsonObj.get("openid").toString());

        String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID";
        requestUrl = requestUrl.replace("ACCESS_TOKEN", jsonObj.get("session_key").toString()).replace(
                "OPENID", jsonObj.get("openid").toString());
        System.out.println(
                requestUrl
        );


        String nickname = ""; //用户昵称
        String sex = "";  //用户的性别
        String province = ""; //用户个人资料填写的省份
        String city = "";  //普通用户个人资料填写的城市
        String country = ""; //国家，如中国为CN
        String headimgurl = ""; //用户头像，
        String unionid = ""; //
        try {
         result= HttpUtil.doGet(requestUrl,null);
   JSONObject json=JSONObject.parseObject(result);
            System.out.println(json+"+==============");
            nickname = json.getString("nickname");
            sex = json.getString("sex");
            province = json.getString("province");
            city = json.getString("city");
            country = json.getString("country");
            headimgurl = json.getString("headimgurl");

            userInfo.setNickName(nickname);
            userInfo.setHeadImg(headimgurl);
            userInfo.setSex(sex);



        } catch (Exception e) {
            e.printStackTrace();
        }


        //将用户信息保存到数据库中
        jzToursUserService.insertJzToursUser(userInfo);
        res.put("userid", jzToursUserService.selectJzToursUserByOpenId(jsonObj.get("openid").toString()).getId());
        return AjaxResult.success(res);
    }




}
